﻿Imports ADOEntityKYC
Imports System.Data

Partial Class Administrator_frmDistrict
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M75"
    Dim sDistrictEntity As KYCEntities
    Dim dsDistrict As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""

#Region " Even Page "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        lblDistrictCode.Text = "รหัสอำเภอ" & " : "
        lblDistrictName.Text = "ชื่ออำเภอ" & " : "
        lblProvince.Text = "จังหวัด" & " : "
        ' ddlProvince.Text = "กรุณาเลือกข้อมูล"
        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsSessionMenuRight = Session("clsMenuRight")

            If (Not IsPostBack) Then
                setUserRightButton()
                CreateControlMP()
                setButton(1)
                loadDataToDropDown()
            Else
                dsDistrict = Session("dsTblMaster")
                gvDistrict.DataSource = dsDistrict.Tables("sDistrict")
                gvDistrict.DataBind()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsDistrict
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "อำเภอ"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLogSearch()
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        ' Response.Redirect("Department.aspx?Status=Add")

        Try
            If chkBeforeSave() Then
                sDistrictEntity = New KYCEntities
                Dim sDistrict As New REFERENCE_CODE_TABLE
                sDistrict.RCRE_TIME = Now
                sDistrict.LCHG_TIME = Now
                sDistrict.LCHG_USER_ID = clsSessionMenuRight.getUserName
                sDistrict.RCRE_USER_ID = clsSessionMenuRight.getUserName
                sDistrict.REF_CODE = ddlProvince.SelectedItem.Value & txtDistrictCode.Text
                sDistrict.REF_DESC = txtDistrictName.Text
                sDistrict.REF_REC_TYPE = "02"
                sDistrict.DEL_FLG = "N"
                sDistrictEntity.AddToREFERENCE_CODE_TABLE(sDistrict)
                sDistrictEntity.SaveChanges()

                SaveLogNew()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)

            End If
        Catch ex As System.Data.UpdateException

            Dim codeError() As String = ex.InnerException.Message.Split(":")
            If codeError(0) = "ORA-00001" Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถเพิ่มได้ เนื่องจากรหัสนี้มีการนำมาใช้ในระบบแล้ว')", True)
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            End If
            WriteError(ex, "btnAdd_Click", "District")
        Catch ex As Exception
            WriteError(ex, "btnAdd_Click", "District")
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)

        End Try
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click


        Try
            If chkBeforeSave() Then
                sDistrictEntity = New KYCEntities
                Dim sProvince As New REFERENCE_CODE_TABLE

                Dim qry = (From province In sDistrictEntity.REFERENCE_CODE_TABLE Where province.REF_CODE = txtDistrictCode.Text).ToList
                qry(0).LCHG_TIME = Now
                qry(0).LCHG_USER_ID = clsSessionMenuRight.getUserName
                'qry(0).REF_CODE = ddlProvince.SelectedItem.Value & txtDistrictCode.Text.Substring(1, 2)
                qry(0).REF_DESC = txtDistrictName.Text
                sDistrictEntity.SaveChanges()

                SaveLogEdit()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            WriteError(ex, "btnModify_Click", "District")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "District")
        End Try


    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (gvDistrict.SelectedIndex = -1) Then
            Dim DepC As String = gvDistrict.Rows(gvDistrict.SelectedIndex).Cells(1).Text
            Try
                sDistrictEntity = New KYCEntities
                Dim qry = (From s_pro In sDistrictEntity.REFERENCE_CODE_TABLE Where s_pro.REF_CODE = DepC).ToList
                qry(0).DEL_FLG = "Y"
                'sDistrictEntity.DeleteObject(qry(0))
                sDistrictEntity.SaveChanges()

                SaveLogDelete(DepC)

                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If
                WriteError(ex, "btnDelete_Click", "District")
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "District")
            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub


#End Region

#Region "Even GridView"

    Protected Sub gvDistrict_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvDistrict.SelectedIndexChanged
        Try
            If (gvDistrict.SelectedIndex = intBeforeItemIndex) Then
                clearGvIndex()
                reset()

                btnModify.Text = "แก้ไข"
            Else
                btnModify.Text = "บันทึก"

                setButton(2)

                txtDistrictCode.Text = gvDistrict.Rows(gvDistrict.SelectedIndex).Cells(1).Text
                txtDistrictName.Text = gvDistrict.Rows(gvDistrict.SelectedIndex).Cells(2).Text
                ddlProvince.Value = gvDistrict.Rows(gvDistrict.SelectedIndex).Cells(1).Text.Substring(0, 2)
                ddlProvince.Enabled = False
                txtDistrictCode.Enabled = False

                btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                           IIf(gvDistrict.SelectedIndex = -1, "", gvDistrict.Rows(gvDistrict.SelectedIndex).Cells(2).Text)) + "');")
            End If
        Catch ex As Exception
            WriteError(ex, "gvProvince_SelectedIndexChanged", "District")
        End Try


    End Sub

    Protected Sub gvDistrict_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvDistrict.SelectedIndexChanging
        intBeforeItemIndex = gvDistrict.SelectedIndex
    End Sub

    Protected Sub gvDistrict_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvDistrict.PageIndexChanging
        gvDistrict.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub gvDistrict_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvDistrict.Sorting
        Dim dt = TryCast(dsDistrict.Tables("sDistrict"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvDistrict.DataSource = dsDistrict.Tables("sDistrict")
            gvDistrict.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub setUserRightButton()
        Dim col As New Collection
        col.Add(btnSearch, statusbtn.Query.ToString)
        col.Add(btnAdd, statusbtn.Add.ToString)
        col.Add(btnModify, statusbtn.Modify.ToString)
        col.Add(btnDelete, statusbtn.delete.ToString)
        setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)

    End Sub

    Private Sub clearGvIndex()
        gvDistrict.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try


            sDistrictEntity = New KYCEntities

            If dsDistrict.Tables.Contains("sDistrict") Then
                dsDistrict.Tables.Clear()
            End If
            Dim qryDis = From Province In sDistrictEntity.REFERENCE_CODE_TABLE
                         Where Province.REF_REC_TYPE = "02" And Province.DEL_FLG = "N"
                        Order By Province.REF_CODE
                        Select Province.REF_CODE, Province.REF_DESC

            If Not (txtDistrictCode.Text = "") Then
                qryDis = qryDis.Where(Function(Dis) Dis.REF_CODE.Contains(txtDistrictCode.Text))
            End If

            If Not (txtDistrictName.Text = "") Then
                qryDis = qryDis.Where(Function(Dis) Dis.REF_DESC.Contains(txtDistrictName.Text))
            End If

            If Not (ddlProvince.SelectedItem Is Nothing) Then
                qryDis = qryDis.Where(Function(Dis) Dis.REF_CODE.StartsWith(ddlProvince.SelectedItem.Value))
            End If

            dsDistrict.Tables.Add(clsDataTable.LINQToDataTable(qryDis, "sDistrict").Copy)

            If (qryDis.Count = 0) Then
                lblMsg.Visible = True
                lblTotal.Text = ""
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + qryDis.Count.ToString + " รายการ "

            End If

            gvDistrict.DataSource = dsDistrict.Tables("sDistrict")
            gvDistrict.DataBind()

            clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "District")

        End Try
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            lblMsg.Visible = False

            btnModify.Enabled = False
            btnDelete.Enabled = False

            btnSearch.Enabled = True
            btnAdd.Enabled = True

            txtDistrictCode.Enabled = True

        ElseIf button = 2 Then 'select

            btnSearch.Enabled = False
            btnAdd.Enabled = False

            btnModify.Enabled = True
            btnDelete.Enabled = True

            txtDistrictCode.Enabled = False

        End If

    End Sub

    Private Sub clear()
        If (dsDistrict.Tables.Contains("sDistrict")) Then
            dsDistrict.Tables("sDistrict").Clear()
            gvDistrict.DataSource = dsDistrict.Tables("sDistrict")
            gvDistrict.DataBind()
        End If
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        ddlProvince.Value = ""
        'loadDataToDropDown()
        txtDistrictCode.Text = ""
        txtDistrictName.Text = ""
        lblTotal.Text = ""
        btnModify.Text = "แก้ไข"
        ddlProvince.Enabled = True
        txtDistrictCode.Enabled = True
    End Sub

    Private Sub reset()
        'gvUserRight.DataSource = dsUserRight.Tables("sUserRight")
        'gvUserRight.DataBind()
        ddlProvince.Value = ""
        'loadDataToDropDown()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtDistrictCode.Text = ""
        txtDistrictName.Text = ""
        ddlProvince.Enabled = True
        txtDistrictCode.Enabled = True
    End Sub

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True

        If (txtDistrictCode.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัสอำเภอ" & "\n"
        ElseIf txtDistrictCode.Text.Length < 2 Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัสอำเภอมากกว่าหนึ่งหลัก" & "\n"
        End If


        If (txtDistrictName.Text = "") Then
            result = False
            strMsg = strMsg & txtDistrictName.Text & " : " & "กรุณาระบุชื่ออำเภอ" & "\n"

        End If

        Return result

    End Function

    Private Sub SaveLogSearch()
        Try


            Dim desc As String = ""

            If Not (txtDistrictCode.Text = "") Then
                desc += " รหัสอำเภอ - " + txtDistrictCode.Text
            End If

            If Not (txtDistrictName.Text = "") Then
                desc += " ชื่ออำเภอ - " + txtDistrictName.Text
            End If


            If Not desc = "" Then
                desc = "ค้นหาข้อมูลอำเภอ จาก " + desc
            Else
                desc = "ค้นหาทั้งหมด"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 1, desc, "M75")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogPrint()
        Try

            Dim desc As String = "พิมพ์ข้อมูลอำเภอ"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 2, desc, "M75")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogNew()
        Try

            Dim desc As String = "บันทึก ข้อมูลอำเภอ (รหัสอำเภอ " + txtDistrictCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtDistrictCode.Text, clsSessionMenuRight.getUserName, 3, desc, "M75")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogEdit()
        Try

            Dim desc As String = "บันทึก แก้ไข ข้อมูลอำเภอ (รหัสอำเภอ " + txtDistrictCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtDistrictCode.Text, clsSessionMenuRight.getUserName, 4, desc, "M75")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogDelete(ByVal value As String)
        Try

            Dim desc As String = "ลบข้อมูลอำเภอ (รหัสอำเภอ " + value + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(value, clsSessionMenuRight.getUserName, 5, desc, "M75")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub loadDataToDropDown()
        Try
            Dim clsDropDown As New clsMasterDropDown
            clsDropDown.setProvince(Me.ddlProvince)
            clsDropDown = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


#End Region

End Class
